<template>
  <view class="container">
    <!-- 顶部导航 -->
    <uni-nav-bar title="疫苗预约" left-icon="back" @clickLeft="back"></uni-nav-bar>

    <!-- 疫苗选择 -->
    <view class="section">
      <view class="section-title">选择疫苗类型</view>
      <scroll-view scroll-x class="vaccine-type-scroll">
        <view v-for="(type, index) in vaccineTypes" :key="index" class="vaccine-type-item"
          :class="{ active: selectedVaccineType === type.id }" @click="selectVaccineType(type.id)">
          <image class="type-icon" :src="type.icon" mode="widthFix"></image>
          <text class="type-name">{{ type.name }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- 疫苗详情 -->
    <view class="section vaccine-detail" v-if="selectedVaccine">
      <view class="detail-header">
        <image class="detail-img" :src="selectedVaccine.image" mode="widthFix"></image>
        <view class="detail-info">
          <text class="detail-name">{{ selectedVaccine.name }}</text>
          <text class="detail-manufacturer">生产厂家：{{ selectedVaccine.manufacturer }}</text>
          <view class="detail-tags">
            <view class="tag">
              <text class="tag-icon">🧪</text>
              <text class="tag-text">需接种{{ selectedVaccine.doses }}剂</text>
            </view>
            <view class="tag">
              <text class="tag-icon">⏱️</text>
              <text class="tag-text">{{ selectedVaccine.intervals }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="detail-description">
        <view class="description-title">疫苗简介</view>
        <view class="description-content">{{ selectedVaccine.description }}</view>
      </view>
      <view class="detail-notes">
        <view class="notes-title">接种注意事项</view>
        <view class="notes-content">
          <view class="note-item" v-for="(note, index) in selectedVaccine.notes" :key="index">
            <text class="note-icon">•</text>
            <text class="note-text">{{ note }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 接种点选择 -->
    <view class="section" v-if="filteredClinics.length > 0">
      <view class="section-title">选择接种点</view>
      <view class="clinic-list">
        <view v-for="(clinic, index) in filteredClinics" :key="index" class="clinic-item"
          :class="{ active: selectedClinicId === clinic.id }" @click="selectClinic(clinic.id)">
          <view class="clinic-info">
            <text class="clinic-name">{{ clinic.name }}</text>
            <text class="clinic-address">{{ clinic.address }}</text>
            <text class="clinic-distance">{{ clinic.distance }}km</text>
          </view>
          <view class="clinic-status">
            <view class="available-count" v-if="clinic.availableCount > 0">
              可预约：{{ clinic.availableCount }}人
            </view>
            <view class="no-available" v-else>
              暂无号源
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 日期选择 -->
    <view class="section" v-if="selectedClinic">
      <view class="section-title">选择接种日期</view>
      <scroll-view scroll-x class="date-scroll">
        <view v-for="(date, index) in availableDates" :key="index" class="date-item" :class="{
          active: selectedDate === date.value,
          disabled: !date.available
        }" @click="selectDate(date.value)">
          <text class="week">{{ date.week }}</text>
          <text class="month-day">{{ date.month }}月{{ date.day }}日</text>
          <text class="status" v-if="!date.available">约满</text>
        </view>
      </scroll-view>
    </view>

    <!-- 时间段选择 -->
    <view class="section" v-if="selectedDate">
      <view class="section-title">选择接种时段</view>
      <view class="time-grid">
        <view v-for="(time, index) in timeSlots" :key="index" class="time-item" :class="{
          active: selectedTime === time.value,
          disabled: !time.available
        }" @click="selectTime(time.value)">
          {{ time.label }}

        </view>
      </view>
      <view class="time-note" v-if="!timeSlots.some(t => t.available)">
        该日期暂无可用时段，请选择其他日期
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitAppointment" :class="{ disabled: !canSubmit }">
      确认预约
    </view>
  </view>
</template>

<script>
import api from '@/api/index.js' // 导入API模块
export default {
  data() {
    return {
      // 疫苗类型
      vaccineTypes: [ ],

      // 疫苗详情
      vaccines: [],

      // 接种点
      clinics: [],

      // 选中状态
      selectedVaccineType: null,
      selectedVaccine: null,
      selectedClinicId: null,
      selectedDate: '',
      selectedTime: '',
      // 动态数据
      availableDates: [],
      timeSlots: []
    };
  },
  computed: {
    // 过滤出支持所选疫苗类型的接种点
    filteredClinics() {
      if (!this.selectedVaccineType) return [];
      return this.clinics.filter(clinic =>
        clinic.vaccineTypeIds.includes(this.selectedVaccineType)
      );
    },

    // 获取选中的接种点信息
    selectedClinic() {
      return this.clinics.find(clinic => clinic.id === this.selectedClinicId) || null;
    },

    // 判断是否可以提交预约
    canSubmit() {
      return this.selectedVaccineType &&
        this.selectedVaccine &&
        this.selectedClinicId &&
        this.selectedDate &&
        this.selectedTime;
    }
  },



  methods: {
    // 选择疫苗类型
    selectVaccineType(id) {
      this.selectedVaccineType = id;
      // 选择该类型下的第一个疫苗作为默认
      console.log('111', this.vaccines);

      this.selectedVaccine = this.vaccines.find(v => v.id === id) || null;
      console.log('222', this.selectedVaccine);
      // 重置后续选择
      this.selectedClinicId = null;
      this.selectedDate = '';
      this.selectedTime = '';
      this.availableDates = [];
      this.timeSlots = [];
    },
    // 选择接种点
    selectClinic(id) {
      this.selectedClinicId = id;
      // 生成该接种点的可用日期
      this.generateAvailableDates();
      // 重置后续选择
      this.selectedDate = '';
      this.selectedTime = '';
      this.timeSlots = [];
    },
    // 生成可用日期（未来14天）
    generateAvailableDates() {
      const dates = [];
      for (let i = 0; i < 14; i++) {
        const date = new Date();
        date.setDate(date.getDate() + i);
        // 模拟日期可用性和配额
        const available = Math.random() > 0.3; // 70%概率有号
        dates.push({
          value: date.toISOString().split('T')[0],
          week: ['日', '一', '二', '三', '四', '五', '六'][date.getDay()],
          month: date.getMonth() + 1,
          day: date.getDate(),
          available
        });
      }
      this.availableDates = dates;
    },
    // 选择日期
    selectDate(date) {
      const selectedDateObj = this.availableDates.find(d => d.value === date);
      if (!selectedDateObj.available) return;
      this.selectedDate = date;
      // 生成该日期的可用时间段
      this.generateTimeSlots();
      this.selectedTime = '';
    },
    // 生成时间段
    generateTimeSlots() {
      // 模拟时间段数据
      this.timeSlots = [
        { label: "08:30-09:30", value: "1", available: Math.random() > 0.4, quota: Math.floor(Math.random() * 10) + 1 },
        { label: "09:30-10:30", value: "2", available: Math.random() > 0.4, quota: Math.floor(Math.random() * 10) + 1 },
        { label: "10:30-11:30", value: "3", available: Math.random() > 0.4, quota: Math.floor(Math.random() * 10) + 1 },
        { label: "13:30-14:30", value: "4", available: Math.random() > 0.4, quota: Math.floor(Math.random() * 10) + 1 },
        { label: "14:30-15:30", value: "5", available: Math.random() > 0.4, quota: Math.floor(Math.random() * 10) + 1 },
        { label: "15:30-16:30", value: "6", available: Math.random() > 0.4, quota: Math.floor(Math.random() * 10) + 1 }
      ];
    },
    // 选择时间段
    selectTime(time) {
      const timeSlot = this.timeSlots.find(t => t.value === time);
      if (timeSlot && timeSlot.available) {
        this.selectedTime = time;
      }
    },
    // 提交预约
    submitAppointment() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完整填写预约信息',
          icon: 'none'
        });
        return;
      }
      // 获取选中项的详细信息
      const selectedVaccineTypeInfo = this.vaccineTypes.find(t => t.id === this.selectedVaccineType);
      const selectedClinicInfo = this.selectedClinic;
      const selectedTimeSlot = this.timeSlots.find(t => t.value === this.selectedTime);

      // 模拟预约提交
      // console.log('提交疫苗预约：', {
      //   vaccineType: selectedVaccineTypeInfo.name,
      //   vaccine: this.selectedVaccine.name,
      //   clinic: selectedClinicInfo.name,
      //   date: this.selectedDate,
      //   time: selectedTimeSlot.label,
      //   availableCount: selectedClinicInfo.availableCount
      // })
      // 准备预约数据
      const appointmentData = {
        vaccineType: selectedVaccineTypeInfo.name,
        vaccine: this.selectedVaccine.name,
        clinic: selectedClinicInfo.name,
        date: this.selectedDate,
        time: selectedTimeSlot.label,
        availableCount: selectedClinicInfo.availableCount
      };
      // 使用封装的API提交预约
      api.submitVaccineAppointment(appointmentData)
        .then(res => {
          // 成功回调
          if (res.code === 200) {
            uni.showToast({
              title: '疫苗预约成功',
              icon: 'success'
            });
            // 2秒后返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          } else {
            // 业务逻辑错误
            uni.showToast({
              title: res.message || '预约失败，请稍后重试',
              icon: 'none'
            });
          }
        })
        .catch(err => {
          // 异常处理 - request.js中已经统一处理了错误提示，这里可以根据需要进行额外处理
          console.error('预约请求异常:', err);
        });



      // 显示预约成功提示
      uni.showToast({
        title: '疫苗预约成功',
        icon: 'success'
      });

    },
    // 获取疫苗类型列表
    async getvaccinetypelist() {
      const res = await api.getVaccineTypeList();
      this.vaccineTypes = res.data;
    },
    async getcliniclist() {
      const res = await api.getClinicList();
      this.clinics = res.data;
    },
    // 同时需要修改getvaccineList方法返回Promise
    async getvaccineList() {
      try {
        const res = await api.getVaccineList();
        this.vaccines = res.data;
        // console.log(this.vaccines);
      } catch (error) {
        console.error('获取疫苗列表失败:', error);
      }
    },



    async onLoad() {
      // 并行获取所有数据
      await Promise.all([this.getcliniclist(), this.getvaccineList(), this.getvaccinetypelist()]);

      // 确保有数据后再选择第一个疫苗类型
      if (this.vaccineTypes.length > 0) {
        this.selectVaccineType(this.vaccineTypes[0].id);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;
}

.section {
  background: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 80rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  &-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    display: flex;
    align-items: center;
    &::before {
      content: '';
      display: inline-block;
      width: 8rpx;
      height: 28rpx;
      background-color: #007aff;
      border-radius: 4rpx;
      margin-right: 12rpx;
    }
  }
}

// 疫苗类型选择
.vaccine-type-scroll {
  white-space: nowrap;
  padding: 10rpx 0;
  .vaccine-type-item {
    display: inline-block;
    width: 140rpx;
    padding: 15rpx 0;
    margin-right: 20rpx;
    border-radius: 12rpx;
    background: #f0f0f0;
    text-align: center;
    transition: all 0.3s;

    &:last-child {
      margin-right: 0;
    }

    &.active {
      background: #007aff;
      color: #fff;
    }
    .type-icon {
      width: 60rpx;
      height: 60rpx;
      margin: 0 auto 10rpx;
      display: block;
    }
    .type-name {
      font-size: 26rpx;
    }
  }
}

// 疫苗详情
.vaccine-detail {
  padding: 25rpx;

  .detail-header {
    display: flex;
    margin-bottom: 30rpx;

    .detail-img {
      width: 200rpx;
      height: 260rpx;
      border-radius: 8rpx;
      margin-right: 25rpx;
      flex-shrink: 0;
    }

    .detail-info {
      flex: 1;

      .detail-name {
        font-size: 34rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 15rpx;
        display: block;
      }
      .detail-manufacturer {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 20rpx;
        display: block;
      }
      .detail-tags {
        display: flex;
        gap: 15rpx;
        flex-wrap: wrap;
        .tag {
          display: flex;
          align-items: center;
          padding: 8rpx 15rpx;
          background-color: #f0f7ff;
          border-radius: 6rpx;
          .tag-icon {
            margin-right: 5rpx;
            font-size: 24rpx;
          }
          .tag-text {
            font-size: 22rpx;
            color: #007aff;
          }
        }
      }
    }
  }

  .detail-description,
  .detail-notes {
    margin-bottom: 30rpx;

    &:last-child {
      margin-bottom: 0;
    }

    .description-title,
    .notes-title {
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
      margin-bottom: 15rpx;
      display: block;
    }
    .description-content {
      font-size: 24rpx;
      color: #666;
      line-height: 1.6;
      text-align: justify;
    }

    .notes-content {
      font-size: 24rpx;
      color: #666;

      .note-item {
        display: flex;
        margin-bottom: 10rpx;
        line-height: 1.5;

        &:last-child {
          margin-bottom: 0;
        }

        .note-icon {
          color: #f43f30;
          margin-right: 10rpx;
          flex-shrink: 0;
        }
      }
    }
  }
}

// 接种点列表
.clinic-list {
  .clinic-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx;
    margin-bottom: 15rpx;
    border-radius: 8rpx;
    background: #f8f8f8;
    transition: all 0.3s;

    &:last-child {
      margin-bottom: 0;
    }

    &.active {
      background: #e3f2fd;
      border: 1rpx solid #007aff;
    }

    .clinic-info {
      flex: 1;

      .clinic-name {
        font-size: 30rpx;
        color: #333;
        font-weight: 500;
        display: block;
        margin-bottom: 5rpx;
      }
      .clinic-address {
        font-size: 24rpx;
        color: #666;
        display: block;
        margin-bottom: 5rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 450rpx;
      }
      .clinic-distance {
        font-size: 22rpx;
        color: #888;
      }
    }

    .clinic-status {
      text-align: right;
      padding-left: 20rpx;

      .available-count {
        font-size: 26rpx;
        color: #007aff;
        font-weight: 500;
      }
      .no-available {
        font-size: 26rpx;
        color: #f43f30;
      }
    }
  }
}

// 日期选择
.date-scroll {
  white-space: nowrap;
  padding: 10rpx 0;
  .date-item {
    display: inline-block;
    width: 120rpx;
    padding: 15rpx 0;
    margin-right: 15rpx;
    border-radius: 8rpx;
    background: #f0f0f0;
    text-align: center;
    position: relative;

    &:last-child {
      margin-right: 0;
    }

    .week {
      display: block;
      font-size: 26rpx;
      margin-bottom: 5rpx;
    }
    .month-day {
      display: block;
      font-size: 28rpx;
      font-weight: 500;
    }
    .quota {
      display: block;
      font-size: 22rpx;
      color: #007aff;
      margin-top: 5rpx;
    }
    .status {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      color: #f43f30;
      font-size: 24rpx;
      display: none;
    }
    &.active {
      background: #007aff;
      color: #fff;
    }

    &.disabled {
      opacity: 0.6;
      background: #f0f0f0;

      .month-day,
      .week,
      .quota {
        opacity: 0.5;
      }

      .status {
        display: block;
      }
    }
  }
}

// 时间段选择
.time-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  .time-item {
    padding: 20rpx 0;
    text-align: center;
    border-radius: 8rpx;
    background: #f0f0f0;
    font-size: 26rpx;
    transition: all 0.2s;
    position: relative;
    .time-quota {
      display: block;
      font-size: 20rpx;
      margin-top: 5rpx;
      color: #666;
    }
    &.active {
      background: #007aff;
      color: #fff;
      transform: scale(1.03);
      .time-quota {
        color: rgba(255, 255, 255, 0.8);
      }
    }
    &.disabled {
      opacity: 0.5;
      background: #f0f0f0;
      color: #999;
    }
  }
}

.time-note {
  text-align: center;
  padding: 30rpx 0;
  color: #f43f30;
  font-size: 26rpx;
}

// 提交按钮
.submit-btn {
  position: fixed;
  bottom: 30rpx;
  left: 30rpx;
  right: 30rpx;
  padding: 25rpx;
  background: #007aff;
  color: #fff;
  text-align: center;
  border-radius: 50rpx;
  font-size: 32rpx;
  font-weight: 500;
  box-shadow: 0 5rpx 15rpx rgba(0, 122, 255, 0.3);
  transition: all 0.3s;
  &.disabled {
    background: #ccc;
    color: #999;
    box-shadow: none;
    pointer-events: none;
  }
  &:active {
    transform: scale(0.98);
  }
}
</style>